/*既然入组切换环境调用*/
import {saveoutbandTask,hostDetail,activeTask} from '@/api/drill.js'
import {queryVmWithParty,queryTargetAllot,} from '@/api/drill_compete.js'
import {getUserDevices} from '@/api/access_new'
const addFlagCommitFun = {
	data(){
		return {
			unusableAutoConfig:false,
			availableSubnetList:[],
			networkArr:[],
	//		canAutoConfig:false,
			flagUsers:[],
			dataVmList:[],
		}
	},
  computed:{
    
  },
  mounted(){
//	this.getTargetTeamList();
//	this.getVmList();
  },
  methods: {
    getAvailableNetwork(group){
			this.unusableAutoConfig = false;
			return new Promise((resolve, reject) => {
	        	group = JSON.parse(group);
		    	let userId =  group.userList.length > 0 ? group.userList[0].userId :'';
		    	if(!userId){
		    		if(this.unusableAutoConfig == true){
		    			return;
		    		}
		    		this.unusableAutoConfig = true;
		    		this.$Message.warning(group.name +'组下没有用户，请先添加用户');
		    		return;
		    	}
		    	getUserDevices(this.$route.query.id,[userId]).then(data => {
		    		let deviceId = data.data.length > 0 ? data.data[0].deviceId :''
		    		if(!deviceId){
		    			//this.$Message.warning('接入组下有用户没有分配机器，请先分配机器');
		    		    return;
		    		}
		    		hostDetail(deviceId).then(data => {
						if(data.code == 1){
							this.availableSubnetList = this.subnetList.filter(sn => sn.id != data.data.networkId)
							console.log(this.availableSubnetList);
							let networkArr = this.availableSubnetList.map(subnet => subnet.id);
							resolve(networkArr);
						}
					})
		    	})
	    	})
	    },
//	    dealAutoConfigData(group){
//  	  let flagUsers = [];
//  		//获取接入组用户分配机器的子网络
//  		this.getAvailableNetwork(JSON.stringify(group)).then(networks => {
//  			let users = group.userList;
//  			let vms = [];
//	    		if(networks && networks.length > 0){
//	    			//获取子网络机器
//	    			vms = this.dataVmList.filter(vm => networks.includes(vm.networkId)).map(vm => vm.id);
//	    		}
//	    		if(vms.length > 0 && users.length > 0){
//	    			for(let i = 0;i<users.length;i++){
//	        			for(let j=0;j<vms.length;j++){
//	        				flagUsers.push({
//	        					accessGroupId:group.id,
//	        					userId:users[i].userId,
//	        					deviceId:vms[j],
//	        					testId:this.$route.query.id
//	        				})
//	        			}
//	        		}
//	    		}
//	    		if(flagUsers.length > 0){
//	    			this.flagUsers = flagUsers;
//	    			this.autoConfig(group);
//	    		}else{
//	    			
//	    		}
//	    	})
//		},
		dealAutoConfigData(curGroup){
        	//循环接入组
        	let index = 0;
        	let flagUsers = [];
        	this.usedAccessList.forEach(group => {
        		//获取接入组用户分配机器的子网络
        		this.getAvailableNetwork(JSON.stringify(group)).then(networks => {
        			let users = group.userList;
        			let vms = [];
	        		if(networks && networks.length > 0){
	        			//获取子网络机器
	        			vms = this.dataVmList.filter(vm => networks.includes(vm.networkId)).map(vm => vm.id);
	        		}
	        		if(vms.length > 0 && users.length > 0){
	        			for(let i = 0;i<users.length;i++){
		        			for(let j=0;j<vms.length;j++){
		        				flagUsers.push({
		        					accessGroupId:group.id,
		        					userId:users[i].userId,
		        					deviceId:vms[j],
		        					testId:this.$route.query.id
		        				})
		        			}
		        		}
	        		}
	        		index ++;
	        		if(index == this.accessGroupList.length && flagUsers.length > 0){
	        			//
	        			this.flagUsers = flagUsers;
	        			this.autoConfig(curGroup);
	        		}
	        	})
        	});
        },
	    autoConfig(group){
			//保存配置
			let params = {
//				auto: true,
	            name:`Flag持续提交(${group.name}切换环境)`,
	            description:'',
	            taskMode:'preset',
	            deviceType:"VM",
	            taskType:'loop_submit_flag',
	            testId:this.$route.query.id,
	            duration:'',
	            flagUsers:this.flagUsers,
	            properties:{},
	        }
			saveoutbandTask(params).then(data => {
				if(data.code == 1){
					this.sendChangeEnvironBoard(group);
					let taskId = data.data.id;
					activeTask(taskId,'start').then((response)=>{
		                if(response.code==1){
		                }else{
		                }
		            })
				}
			})
			
	    },
//	    addFlagOutLoopTask(group){
//	    	let params = {
//	    		name:`Checker任务(${group.name}切换换环境)`,
//	            // configName:$this.configPanel.configName,
//	            // configId:$this.formValidate.configer.split('-')[0],
//	            description :$this.formValidate.desc,
//	            deviceData:$this.selectedVmDataTable.map(vmId => {
//	            	return {
//	            		deviceId:vmId,
//	            		deviceType:"VM"
//	            	}
//	            }),
//	            deviceIdList :$this.selectedVmDataTable,
//	            deviceType:"VM",
//	            taskType:$this.taskTypeTable,
//	            taskMode:$this.formValidate.taskMode,
//	            testId:$this.currentSceneId,
//	            metadata:{
//	                scriptId:$this.formValidate.configer,
//	                interval:Number($this.formValidate.expireTime),
//	                serverPort:$this.formValidate.serverPort
//	            },
//	        }
//	    },
        getTargetTeamList(){
    		return new Promise((resolve,reject) => {
				let params = {
					pageIndex:1,
					pageSize:2147483647,
					sceneId:this.$route.query.id,
				}
				queryTargetAllot(params).then(data => {
		  			if(data.code==1){
		  				this.targetAllotList = data.data.items;
		   				this.targetAllotTotal = data.data.total;
		  				let targetList = data.data.items || data.data;
		  				resolve(targetList);
		  			}else{

		  			}
		  		})
	  		})
	  	},
	  	getVmList(group){
        	return new Promise((resolve,reject) => {
            	let $this = this;
            	let params = {
					page:1,
					pageSize:100000,
					sortBy:'name',
					order:'asc',
					findPorts:true,
				};
				queryVmWithParty(this.$route.query.prjid,params).then((response)=>{
                	$this.dataVmList = [];
                	if(response.code==1){
                    	let vmData = response.data.list;
	                    this.getTargetTeamList().then(targetList => {
	                    	let targetIds = targetList.map(target => target.vmId);
		                    vmData.forEach(function(item,i){
		                        if(targetIds.includes(item.id)){
			                        $this.dataVmList.push({
			                            name:item.name,
			                            id:item.id,
			                            sysType:item.sysType,
			                            networkId:item.networkId,
			                            networkName:item.networkName,
			                            profile:item.profile = item.profile ? item.profile :'',
			                            IP:item.address.map((item)=>item.ips.map(ip => ip.ipAddress).join(',')),

			                        })
		                        }
		                    })
		                    this.dealAutoConfigData(group);
		                    resolve();
	                    })
                	}
            	})
			})
        },
    }
}
export default addFlagCommitFun
